<?php

namespace App\Http\Controllers\Web;

use App\Services\Role;
use App\Http\Requests\RoleRequest;
use Illuminate\Http\Request;

/**
 * Class RoleController 角色控制器
 * @package App\Http\Controllers\Admin
 */
class RoleController extends BaseController
{
    /**
     * RoleController constructor.
     */
    public function __construct()
    {
        $this->service = Role::getInstance();
    }

    /**
     * index 角色列表
     * @param RoleRequest $request
     * @return object
     * @throws \Exception
     */
    public function index(RoleRequest $request)
    {
        // 关键词搜索
        if (!empty($request->get('keyword'))) {
            $condition[] = ['roles.name', 'like', '%' . $request->get('keyword') . '%'];
        }
        // 状态值匹配
        if (!empty($request->get('status'))) {
            $condition[] = ['status', '=', $request->get('status')];
        }

        $list = $this->service->getList($condition ?? []);

        return $this->success('查询成功', $list);
    }

    /**
     * store 新增角色
     * @param RoleRequest $request
     * @return object
     * @throws \Exception
     */
    public function store(RoleRequest $request)
    {
        $this->service->insertData($request->all());

        return $this->success('新增成功', []);
    }

    /**
     * update 更新角色
     * @param RoleRequest $request
     * @param int $id
     * @return object
     * @throws \Exception
     */
    public function update(RoleRequest $request, int $id)
    {
        $this->service->updateData($id, $request->all());

        return $this->success('更新成功',[]);
    }

    /**
     * menus 获取角色拥有的二级菜单
     * @param RoleRequest $request
     * @param int $role_id
     * @return object
     */
    public function menus(RoleRequest $request, int $role_id)
    {
        $result = $this->service->getRoleSecondMenus($role_id);

        return $this->success('获取成功', $result);
    }

    /**
     * permissions 角色在某个菜单拥有的节点情况
     * @param RoleRequest $request
     * @param int $role_id
     * @param int $menu_id
     * @return object
     */
    public function permissions(RoleRequest $request, int $role_id, int $menu_id)
    {
        $result = $this->service->getRolePermissions($role_id, $menu_id);

        return $this->success('获取成功', $result);
    }

    /**
     * rolePermission 保存角色拥有的节点权限
     * @param Request $request
     * @return object
     * @throws \Exception
     */
    public function rolePermission(Request $request)
    {
        $result = $this->service->saveRolePermission($request->all());

        return $this->success('保存成功', []);
    }
}
